{layout name="public/layout" /}
{include file='yxnavbar'}


<style>
    .mobile_style{
        background: url("{$mobile_bg_img}");
        background-size: contain;
        /*background-size: 296px 609px;*/
        background-repeat: no-repeat;
        width: 336px;
        height: 609px;
        border-radius: 40px;
        -webkit-box-shadow: 1px 2px 24px 0 rgba(0,0,0,.08);
        box-shadow: 1px 2px 24px 0 rgba(0,0,0,.08);
        border: 1px solid lightgray;
        position: relative;
    }
    .sms_title{
        margin-left: 25%;
        font-size: 22px;
        font-weight: 600;
        height: 50px;
        line-height: 30px;
    }
    .mode_change{
        display: flex;flex-direction: column;
        margin-top: 80px;
        width: 28px;
        margin-right: 1%;
    }
    .mode_change_item{
        text-align: center;
        padding: 8px;
        background-color: #e6ebed;
        margin-top: 4px;
    }
    .mode_change_item_active{
        background-color: #428bca !important;
        color: #fff !important;
    }
    .mobile_container{
        height: 400px;
        position: absolute;
        width: 94%;
        top: 104px;
        left: 8px;
    }
    .mobile_containe_content{
        position: absolute;
        left: 20px;
        max-width: 232px;
        padding: 8px 10px;
        color: #333;
        background-color: #e9e9eb;
        border-radius: 16px;
        word-break: break-all;
    }
    .mobile_containe_content:before{
        content: " ";
        display: inline-block;
        position: absolute;
        background-image: url("{$mobile_msg_img}");
        background-repeat: no-repeat;
        width: 18px;
        height: 10px;
        left: -5px;
        bottom: 0;
    }
    .mobile_container_edit{
        padding: 10px 2px 0;
    }
    .mobile_container_edit_main{
        position: relative;
        box-sizing: border-box;
    }
    .mobile_container_edit_main_label{
        position: absolute;
        top: 7px;
        left: 5px;
        z-index: 1;
        box-sizing: border-box;
    }
    .mobile_container_edit_main_textarea{
        min-height: 206px;
        max-height: 288px;
        text-indent: 87px;
        border-radius: 4px;
        position: relative;
        display: inline-block;
        width: 100%;
        border: 1px solid #ccd5db;
        padding: 5px 10px;
        color: rgba(0,0,0,.65);
        text-indent: 50px;
        line-height: 1.5;
    }
    .sms_content_tips{
        min-height: 100px;
        border-radius: 4px;
        padding: 12px;
        font-size: 14px;
        line-height: 20px;
        margin-left: 6%;
        background-color: #e7f4ff;color: #666;
        display: none;
    }
    .sms_content_tips_danger{
        min-height: 100px;border-radius: 4px;padding: 12px;color: #ff5448;font-size: 14px;line-height: 20px;margin-left: 6%;margin-top: 10px;
        display: none;
    }
    .mobile_container_edit_main_span{
        position: absolute;
        right: 16px;
        bottom: 6px;
        font-size: 12px;
        color: #999;
        line-height: 17px;
    }
</style>
<div class="main">
    {include file='sms/sms_header'}

    <div class="panel panel-info">
        <div class="panel-body" style="display: flex;flex-direction: row;">
            <div style="width:70%">
                <form action="" method="post" class="form-horizontal" role="form" name="form2" id="form2">
                    <input type="hidden" name="themeid" value="{$themeid}"/>
                    <div class="form-group">
                        {if $no_pass_tips}<label ><span style="color: red;">{php echo $no_pass_tips;}</span></label>{/if}
                    </div>
                    <div class="form-group">
                        <label class="col-sm-1 col-md-1 col-lg-1 control-label">导入手机号</label>
                        <div class="col-sm-10 col-xs-12">
                            <table id="import_data" lay-filter="import_data"></table>
                        </div>
                    </div>
                    <input type="hidden" name="diy_template_params" id="diy_template_params" value="">
                    <input type="hidden" name="show_template_params" id="show_template_params" value="">
                    <input type="hidden" name="template_content" id="sure_out_template_content" value="">

                    <div class="form-group">
                        <label class="ol-sm-1 col-md-1 col-lg-1 control-label">短信内容</label>
                        <div class="col-sm-10 col-xs-12">
                            <div  >
                                <div style="display: flex;flex-direction: column;">
                                    <textarea id="out_template_content" name="out_template_content" rows="8" maxlength="300" ></textarea>
<!--                                    <span class="help-block" ><span id="out_template_content_count">300</span></span>-->
<!--              <span class="help-block" style="color: blue;" >发送时将按照实际发送短信内容计费，每67个字符为一条短信，请合理规划短信内容</span>-->
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-1 col-md-1 col-lg-1 control-label">插入列</label>
                        <div class="col-sm-10 col-xs-12">
                             <span id="quick_cols"></span>
                             <button  class="layui-btn layui-btn-primary layui-border-green" onClick="insertSmsTag(this)" type="button" data-type="活动网址">活动网址</button>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-1 col-xs-12 control-label">定时发送</label>
                        <div class="col-sm-10  col-xs-12">
                            <label class="radio-inline">
                                <input name="delayed_send" class="delayed_send"  value="0" checked="checked" type="radio">关闭
                            </label>
                            <label class="radio-inline">
                                <input name="delayed_send" class="delayed_send" value="1" type="radio">开启
                            </label>
                        </div>
                    </div>
                    <div class="form-group" id="showDelaedTime" style="display: none">
                        <label class="col-sm-1 col-md-1 col-lg-1 control-label">发送时间</label>
                        <div class="col-sm-2 col-xs-12">
                            <input type="text" class="form-control"  placeholder="选择日期" id="delayed_date" name="delayed_date"  value="">
                        </div>
                        <div class="col-sm-2 col-xs-12">
                            <input type="text" class="form-control"  placeholder="选择时间" id="delayed_time" name="delayed_time"  value="">
                        </div>
                    </div>

                    <div class="form-group" id="sub_upload" text-align="center" >
                        <div class="col-sm-12" >
                            <input name="submit" onclick="addOrEditItem()"  id="btnConfirm" type="button" value="确认提交" class="btn btn-primary col-lg-2">
                            <input name="submit" id="preview"  type="button" value="预览" class="btn btn-warm col-lg-1">
                        </div>
                    </div>
                </form>
            </div>

            <div  style="width:30%">
                <div style="display: flex;flex-direction: row;">
                    <div class="mobile_style" >
                        <div class="mobile_container">
                            <div class="mobile_container_edit" style="display: none;">
                                <div class="mobile_container_edit_main">
                                    <label class="mobile_container_edit_main_label">{php echo $sign_name;}</label>
                                    <textarea class="mobile_container_edit_main_textarea" maxlength="500" id="quick_template" {if $wait_item['out_template_content']}readonly="readonly"{/if}>{$wait_item['out_template_content']}</textarea>
                                    <span class="mobile_container_edit_main_span"><span class="input_text_length">6</span>/500</span>
                                </div>
                                <div style="display: flex;flex-direction: row;justify-content: space-around;">
                                    <div style="color: #666;font-size: 12px;text-shadow: rgba(0,0,0,0.08);">请在 <span>{php echo $sign_name;}</span>之后输入内容</div>
                                    <div style="color: #1261ff;font-size: 12px;text-shadow: rgba(0,0,0,0.08);">短信制作规范</div>
                                </div>
                            </div>
                            <div class="mobile_containe_content" ></div>
                            <div class="mobile_container_edit_main_span"><span class="input_text_length">6</span>/500</div>
                        </div>
                    </div>
                    <div style="width: 40%;margin-top: 12%;" >
                        <div  class="sms_content_tips" >
                            计费：当前设置的短信内容，每次发送会消耗<span class="sms_content_tips_sms_total">1</span>条短信，计费<span class="sms_content_tips_sms_amount">0.2</span>元,<a style="color: #428bca;" onclick="showSmsPriceDesc();" href="#">点击查看</a>计费方式
                        </div>
                        <div class="sms_content_tips_danger">
                            计费：当前设置的短信内容，每次发送会消耗一条短信，计费0.1元,计费方式
                        </div>
                    </div>
                </div>
            </div>
            </div>
        </div>
    </div>
</div>

<script type="text/html" id="toolbar">
      <div>
          <a class="layui-btn layui-btn-sm layui-btn-normal" href="https://css2020.yixuan.net/2020css/yx2020/sms/群发短信模板.xlsx" >下载模板</a>
          <a class="layui-btn layui-btn-sm" id="import" lay-event="import">导入数据</a>
          <span  class="layui-word-aux">1.第一列必须是手机号，第一行为标题 2. 最大支持1万条数据 3.支持xls和xlsx格式</span>
      </div>
       合格号码数：<span id="right_mobile_num">0</span> 个, 重复号码数 <span id="repeatd_mobile_num">0</span> 个,不合格号码数：<span id="unqualified_mobile_num">0</span> 个
</script>

<div class="preview"  id="showContent" style="display: none;">
    <div class="panel-body">
        <table id="preview_data" lay-filter="preview_data"></table>
    </div>
</div>

<script type="text/javascript">
    var all_data = {};
    var quick_cols = [];
    var head = "【{$sign_name}】";
    var tail = '拒收请回复R';
    var show_text1 = "【{php echo $sign_name;}】";
    var open_yx_sms = "{php echo $open_yx_sms;}";
    var act_url =  "{$index_url}";

    $('.delayed_send').on('change',function () {
        showDelaedTime(this.value);
    });
    function showDelaedTime(val) {
        if(val==1){
            $('#showDelaedTime').show();
        }else{
            $('#showDelaedTime').hide();
        }
    }

    var sms_name_total =0,sms_address_total=0,sms_time_total=0,sms_shop_total=0,sms_desc_total=0;
    //新增\修改
    $("#out_template_content").on("input propertychange",function () {
        var that = $(this);
        var content = that.val();
        var count = '';
        if (content.length>300){
            that.val(content.substring(0,300));
        }
        count = 300 - content.length;
        $("#out_template_content_count").text(count);
    });

    function inLimitTxtLength(str) {
        var tmp_content_length = $("#out_template_content").val().length;
        var input_txt_length = str.length;
        if (tmp_content_length+input_txt_length>500){
            return false;
        }
        return true;
    }
    //插入短信标签
    function insertSmsTag(e) {
        let tmp_val= '';
        let lay_msg = '超过文字长度限制';
        let tmp_type = e.getAttribute("data-type");
        tmp_val='#'+tmp_type+'#';
        if (!inLimitTxtLength(tmp_val)){
             layer.msg(lay_msg);
             return
        }
        //追加文本
        $("#out_template_content").insertAtCaret(tmp_val);
        changeSms($("#out_template_content").val());
    }


    (function ($) {
        $.fn.extend({
            insertAtCaret: function (myValue) {
                var $t = $(this)[0];
                if (document.selection) {
                    this.focus();
                    sel = document.selection.createRange();
                    sel.text = myValue;
                    this.focus();
                } else
                if ($t.selectionStart || $t.selectionStart == '0') {
                    var startPos = $t.selectionStart;
                    var endPos = $t.selectionEnd;
                    var scrollTop = $t.scrollTop;
                    $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
                    this.focus();
                    $t.selectionStart = startPos + myValue.length;
                    $t.selectionEnd = startPos + myValue.length;
                    $t.scrollTop = scrollTop;
                } else {
                    this.value += myValue;
                    this.focus();
                }
            }
        })
    })(jQuery);


    function addOrEditItem() {
        sureTemplate();
        let postUrl = "{php echo createWebUrl('sms',array('op'=>'personal_send','themeid'=>$themeid));}";
        let success_redirect = "{php echo createWebUrl('sms',array('op'=>'sendlog','themeid'=>$themeid));}";
        let themeid = $('#themeid').val();

        let diy_template_params = $('#diy_template_params').val();
        let show_template_params = $('#show_template_params').val();
        let template_content = $('#sure_out_template_content').val();
        let out_template_content = $('#out_template_content').val();
        let delayed_send =  $("input[name='delayed_send']:checked").val();
        let delayed_time = $('#delayed_time').val();
        let delayed_date = $('#delayed_date').val();
        if(delayed_send==1){
            delayed_time = delayed_date+' '+delayed_time;
        }

        $.ajax({
            url:postUrl,
            dataType:'json',
            method:'post',
            data:{
                themeid:themeid,
                diy_template_params:diy_template_params,
                show_template_params:show_template_params,
                template_content:template_content,
                out_template_content:out_template_content,
                delayed_send:delayed_send,
                delayed_time:delayed_time,
                order_list:all_data,
                quick_cols:quick_cols
            },
            success:function (e) {
                let status = e.status;
                let result = e.result;
                if (status!=1){
                    layer.msg(result.msg)
                }else{
                    layer.msg(result.msg);
                    window.location.href = success_redirect;
                }
            },
            fail:function (err) {
              console.log(err)
            }
        })
    }
    //格式化参数
    function sureTemplate(){
        var diy_template_params = '';
        var show_template_params = '';
        var tmp_temp_txt = $("#out_template_content").val();
        var format_tmp_temp_txt = $("#out_template_content").val();
        var m = tmp_temp_txt.split("#");
        m.shift();
        m.forEach(function (val) {
            // var reg = /[^\x00-\xff]/ig;
             if (quick_cols.indexOf(val)>-1){
                diy_template_params += val+',';
                search_txt_item = '#'+val+'#';
                show_template_params += '#'+val+'#,';
                replace_txt_item = '{%'+val+'%}';
                format_tmp_temp_txt = format_tmp_temp_txt.replace(search_txt_item,replace_txt_item);
            }else if(val=='活动网址'){
                 diy_template_params += val+',';
                 search_txt_item = '#'+val+'#';
                 show_template_params += '#'+val+'#,';
                 replace_txt_item = '{%'+val+'%}';
                 format_tmp_temp_txt = format_tmp_temp_txt.replace(search_txt_item,replace_txt_item);
             }
        })
        if (diy_template_params.length>0){
            diy_template_params = diy_template_params.substring(0,diy_template_params.length - 1);
        }
        if (show_template_params.length>0){
            show_template_params = show_template_params.substring(0,show_template_params.length - 1);
        }
        $("#show_template_params").val(show_template_params);
        $("#diy_template_params").val(diy_template_params);
        $("#sure_out_template_content").val(format_tmp_temp_txt);
    }
    //时间选择
    layui.use(['layer','table','laydate','upload'],function () {
        var laydate = layui.laydate;
        var table = layui.table;
        var upload = layui.upload;
        var layer = layui.layer;
        var myDate = new Date();  //获取当前时间
        laydate.render({
            elem: '#delayed_date'
            ,type: 'date'
            ,min:myDate.toLocaleString()  //转化当前时间格式
            ,max: 7 //7天后
            ,done: function(value, date, endDate){
                var myTime = new Date();
                var lastHour =   myTime.setHours(myTime.getHours() + 1);
                var lastTime = new Date(lastHour);
                var hour = lastTime.getHours();
                $('#delayed_time').val(hour+':00:00');
                selTime.config.min = myTime.toLocaleString();
            }
        });

       var selTime = laydate.render({
            elem: '#delayed_time'
            ,type: 'time'
            ,min:myDate.toLocaleString()  //转化当前时间格式
        });
        //第一个实例
        var tableIns = table.render({
            elem: '#import_data'
            ,height: 240
            ,toolbar: '#toolbar'
            ,defaultToolbar:[]
            ,data:[]
            ,page: false  //开启分页
            ,cols: [[ //表头
                {field: 'mobile', title: '手机号', width:110,}
                ,{field: 'function1', title: '参数1', width:0}
                ,{field: 'function2', title: '参数2', width:0}
                ,{field: 'function3', title: '参数3', width:0}
                ,{field: 'function4', title: '参数4', width: 0}
            ]]
        });

        let postUrl = "{php echo createWebUrl('sms',array('op'=>'import','themeid'=>$themeid));}";
        upload.render({
            elem: '#import'
            , accept: 'file'
            , exts:'xls|xlsx'
            , url: postUrl
            , before: function (obj) {
                layer.msg('文件上传中...', {
                    icon: 16,
                    shade: 0.01,
                    time: 0
                })
            }
            , done: function (data) {
                if (data.status == 1){
                    var res_data = data.result.data;
                    tableIns.reload({
                        cols : [res_data.table_cols],
                        data : res_data.table_data
                    });
                    var select_data = res_data.select_data;
                    var quick_cols_html = '';
                    $.each(select_data,function (index,item) {
                        quick_cols_html += `<button  class="layui-btn layui-btn-primary layui-border-green" onClick="insertSmsTag(this)" type="button" data-type="${item}">${item}</button>`;
                    });

                    all_data = res_data.all_data;
                    quick_cols = select_data;
                    $('#quick_cols').html(quick_cols_html);
                    //$('#order_list').val(all_data);
                    $('#right_mobile_num').html(res_data.right_mobile_num);
                    $('#unqualified_mobile_num').html(res_data.unqualified_mobile_num);
                    $('#repeatd_mobile_num').html(res_data.repeatd_mobile_num);
                    layer.msg(data.result.msg, {icon: 6});
                } else {
                     layer.msg(data.result.msg, {icon: 5});
                     window.location.reload();
                }
            }
            , error: function () {
                layer.msg('网络请求出现错误！', {icon: 5});
            }
        });

        //预览
        $('#preview').click(function (){
            if(all_data.length==0){
                layer.msg('请上传数据');
                return false;
            }
            let content = $('#out_template_content').val();
            if(content.length==0){
                layer.msg('请输入短信内容');
                return false;
            }

            infoOpen = layer.open({
                type: 1,
                title: '短信预览',
                closeBtn: 1,
                anim: 2,
                shadeClose: true,
                area: ['80%', '600px'],
                content: $("#showContent"),
                btn: false,
                zIndex: 1000,
                success: function (layero, index) {
                    var sign_name = "【{$sign_name}】";
                    var params = [];
                    var params_key = [];
                    var has_url = false;

                    var m = content.split("#");
                    m.forEach(function (val) {
                        var key =  quick_cols.indexOf(val)
                        if (key>-1){
                            params.push('#'+val+'#');
                            params_key.push(key);
                        }else if(val=='活动网址'){
                            has_url = true;
                        }
                    });

                    var perview_data = [];
                    $.each(all_data,function (i,val) {
                        if(i<10){
                            var mobile = val[0];
                            var user_content = content;
                            params_key.forEach(function (vv){
                                var col =  '#'+quick_cols[vv]+'#';
                                var data = val[vv];
                                user_content = user_content.replace(col,data)
                            });
                            if(has_url){
                                user_content = user_content.replace('#活动网址#',act_url)
                            }
                            user_content = sign_name + user_content+' 退回T';
                            var smsNum = checkNum(user_content);
                            perview_data.push(
                                {
                                    'mobile':mobile,
                                    'content':user_content,
                                    'code_num':smsNum.code_num,
                                    'send_num':smsNum.send_num,
                                }
                            )
                        }
                    });

                    var tableIns = table.render({
                        elem: '#preview_data'
                        ,height: 500
                        ,data:perview_data
                        ,page: false  //开启分页
                        ,cols: [[ //表头
                            {field: 'mobile', title: '手机号', width:130}
                            ,{field: 'content', title: '内容', width:0}
                            ,{field: 'code_num', title: '字数', width:60}
                            ,{field: 'send_num', title: '条数', width:60}
                        ]]
                    });
                }
            })
        });
    });

    $(document).ready(function () {
        var default_str_length = 4;
        var input_text = $('#out_template_content').val();
        var input_text_length = input_text.length;
        var total_text_length = default_str_length+input_text_length+head.length+tail.length;
        if (input_text_length<1){
            $('.sms_content_tips').hide();
            $('.sms_content_tips_danger').hide();
        }
        var sms_content_tips_sms_total=1;
        var sms_content_tips_sms_amount = '0.1';
        if (input_text_length>0){
            sms_content_tips_sms_total = Math.ceil(total_text_length/67);
            sms_content_tips_sms_amount = sms_content_tips_sms_total/10;
            $('.sms_content_tips_sms_total').html(sms_content_tips_sms_total);
            $('.sms_content_tips_sms_amount').html(sms_content_tips_sms_amount);
            $('.sms_content_tips').show();
        }
        if(tail=='undefined'&&head=='undefined'){
            var show_text =  show_text1+$(this).val();
        }else{
            var show_text =  show_text1+$(this).val()+tail;
        }
        $('.input_text_length').html(total_text_length);
        $('.mobile_containe_content').html(show_text);
    });

    $("#out_template_content").keyup(function () {
        changeSms($(this).val());
    });

    //内容变化处理方法
    function changeSms(content){
        var default_str_length = 0;
        var sms_content = content;
        if (sms_content.length<1){
            $('.sms_content_tips').hide();
            $('.sms_content_tips_danger').hide();
        }

        if(all_data.length>0){
            var params = [];
            var params_key = [];
            var has_url = false;
            var m = sms_content.split("#");
            m.forEach(function (val) {
                var key =  quick_cols.indexOf(val)
                if (key>-1){
                    params.push('#'+val+'#');
                    params_key.push(key);
                }else if(val=='活动网址'){
                    has_url = true;
                }
            });

            var perview_data = all_data[0];
            params_key.forEach(function (vv){
                var col =  '#'+quick_cols[vv]+'#';
                var data = perview_data[vv];
                sms_content = sms_content.replace(col,data)
            });
            if(has_url){
                sms_content = sms_content.replace('#活动网址#',act_url)
            }
        }
        var input_text_length = sms_content.length;
        var total_text_length = default_str_length+input_text_length+head.length+tail.length;
        if (total_text_length>=500){
            layer.msg('最大输入500个字符');
            return false;
        }

        var sms_content_tips_sms_total=1;
        var sms_content_tips_sms_amount = '0.1';
        if (input_text_length>0){
            sms_content_tips_sms_total = Math.ceil(total_text_length/67);
            sms_content_tips_sms_amount = sms_content_tips_sms_total/10;
            $('.sms_content_tips_sms_total').html(sms_content_tips_sms_total);
            $('.sms_content_tips_sms_amount').html(sms_content_tips_sms_amount);
            $('.sms_content_tips').show();
        }
        if(tail=='undefined'&&head=='undefined'){
            var show_text =  show_text1+sms_content;
        }else{
            var show_text =  show_text1+sms_content+tail;
        }

        $('.input_text_length').html(total_text_length);
        $('.mobile_containe_content').html(show_text);
    }

    //文本域输入文字加默认短信模版头长度计数
   function  checkNum(content) {
        var total_text_length = content.length;
        if (total_text_length>=500){
            layer.msg('最大输入500个字符');
            return false;
        }
        var sms_content_tips_sms_total=1;
        if (total_text_length>0){
            sms_content_tips_sms_total = Math.ceil(total_text_length/67);
        }
        var res = {
            'code_num':total_text_length,
            'send_num':sms_content_tips_sms_total
        };
        return res;
   }
</script>
